module es {
    /**
     * 所有的 TimelineSprite 对象 统一调度管理 
     * 全局只产生一个定时器
     */
    export class TimelineFactory {

        /**
         * 减少内存碎片 使用单例管理一个类申请的所有内存
         */
        private static instance: TimelineFactory;
        private elements: TimelineSprite[] = [];
        /**
         * 不允许自行创建
         */
        private constructor() { };
        /**
         * 不允许业务逻辑自行创建
         */
        private static genSingleton() {
            TimelineFactory.instance = new TimelineFactory();
            Laya.timer.frameLoop(1, TimelineFactory.instance, TimelineFactory.instance.update);
        }

        /**
         * 更新
         */
        private update() {
            if (this.elements.length > 0) {
                let element: TimelineSprite, delta = Laya.timer.delta;
                for (let i = 0; i < this.elements.length; i++) {
                    element = this.elements[i];
                    element['tm'] += delta;
                    if (element['tm'] >= element['interval']) {
                        element['tm'] -= element['interval'];
                        element['updateFrame']();
                    }
                }
            }
        }

        public appendTimeline(timeline: TimelineSprite) {
            let index = this.elements.indexOf(timeline);
            if (index == -1) {
                this.elements.push(timeline);
            }
        }

        public removeTimeline(timelineOrIndex: TimelineSprite | number) {
            if (typeof timelineOrIndex == "number") {

                if (timelineOrIndex >= 0 && timelineOrIndex < this.elements.length) {

                    this.elements.splice(timelineOrIndex, 1);
                }
            }
            else {

                let index = this.elements.indexOf(timelineOrIndex);
                if (index != -1) {
                    this.elements.splice(index, 1);
                }
            }
        }

        /**
         * 主动释放  
         * 一般情况下 整个游戏生命周期内 都不需要调用 你可以忽视它
         */
        public release() {
            this.elements = [];
            Laya.timer.clear(TimelineFactory.instance, TimelineFactory.instance.update);
        }
    }
}